package com.rytx.system.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.github.pagehelper.util.StringUtil;
import com.rytx.common.core.domain.AjaxResult;
import com.rytx.common.utils.uuid.MyIncrementGenerator;
import com.rytx.system.domain.ysp.ArtMessage;
import com.rytx.system.domain.ysp.ArtOrder;
import com.rytx.system.domain.ysp.ArtServiceCharge;
import com.rytx.system.mapper.ArtMessageMapper;
import com.rytx.system.mapper.ArtOrderMapper;
import com.rytx.system.mapper.ArtServiceChargeMapper;
import com.rytx.system.refund.BuyAfterRefund;
import com.rytx.system.refund.IAfterRefund;
import com.rytx.system.refund.LeaseAfterRefund;
import com.rytx.system.service.IArtAfterLogService;
import com.rytx.system.service.IArtOrderService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rytx.system.mapper.ArtOrderAfterMapper;
import com.rytx.system.domain.ArtOrderAfter;
import com.rytx.system.service.IArtOrderAfterService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 售后订单Service业务层处理
 *
 * @author rytx
 * @date 2024-08-29
 */
@Service
public class ArtOrderAfterServiceImpl implements IArtOrderAfterService
{
    @Autowired
    private ArtOrderAfterMapper artOrderAfterMapper;//售后表
    @Autowired
    private IArtAfterLogService artAfterLogService;//操作记录表
    @Autowired
    private IArtOrderService artOrderService;//订单表
    @Autowired
    private BuyAfterRefund BuyAfterRefund;//购买售后操作
    @Autowired
    private LeaseAfterRefund LeaseAfterRefund;//租赁售后订单
    @Autowired
    private ArtOrderMapper artOrderMapper;
    @Autowired
    private ArtMessageMapper artMessageMapper;

    @Autowired
    private ArtServiceChargeMapper artServiceChargeMapper;

    /**
     * 解冻订单失败处理：重新解冻订单
     * */
    @Override
    public void afterUnfreezeFailTask() {
        ArtOrderAfter artOrderAfter = new ArtOrderAfter();
        artOrderAfter.setStatus(IArtAfterLogService.ORDER_STATUS_SETTLEMENT_EXCEPTION);
        List<ArtOrderAfter> artOrderAfters = artOrderAfterMapper.selectArtOrderAfterList(artOrderAfter);
        for (ArtOrderAfter after : artOrderAfters) {//解冻失败的订单
            ArtOrder order = artOrderService.getOrderByOrderNo(after.getPlatOrderNo());
            LeaseAfterRefund.reSettle(after,order);
        }
    }

    /**
     * 撤销售后
     * @param artOrderAfter
     */
    @Transactional
    @Override
    public String cancelOrderAfter(ArtOrderAfter artOrderAfter) {
        int i = artOrderAfterMapper.updateAfterStatusByOrderNo(artOrderAfter.getPlatOrderNo());
        int j = artOrderMapper.updateAfterStatusByOrderNo(artOrderAfter.getPlatOrderNo());
        return "撤销成功";
    }

    @Override
    @Transactional
    public AjaxResult updateOrderAfterStatus(ArtOrderAfter artOrderAfter) {
        AjaxResult ajaxResult = AjaxResult.success();
        /**
         * 实现思路？
         * 1. 校验参数
         * 2. 查询出订单来
         * 3.判断这个售后订单是什么类型然后进行对应的操作
         * */
        //查询出订单

        checkUpdateAfterStatusParams( artOrderAfter);
        String platAfterNo = artOrderAfter.getPlatAfterNo();
        ArtOrderAfter AfterOrder = artOrderAfterMapper.getAfterOrderByAfterOrderNo(platAfterNo);
        AfterOrder.setCompensationAmount(artOrderAfter.getCompensationAmount());
        if(AfterOrder == null){
            throw new RuntimeException("售后订单状态完结或不存在");
        }
        String platOrderNo = AfterOrder.getPlatOrderNo();
        ArtOrder artOrder = artOrderService.getOrderByOrderNo(platOrderNo);
        Long status = artOrderAfter.getStatus();
        if(2 == status.longValue()){//售后中
            ajaxResult =  updateAfterStatusToUnderway(AfterOrder,artOrder);
        }else if(3 == status.longValue()){//已完成  todo !!!
             ajaxResult = updateAfterStatusToFinish(AfterOrder, artOrder);
        }else if(4 == status.longValue()){  //已关闭
            ajaxResult = updateAfterStatusToClose(AfterOrder,artOrder);//暂时用不上
        }else if(5 == status.longValue()){//审核驳回
            ajaxResult = updateAfterStatusToReject(AfterOrder,artOrder);
        }else if(6 == status.longValue()){//已取消
            ajaxResult = updateAfterStatusToCancel(AfterOrder,artOrder);//暂时用不上，小程序用户用的，但可能用不上
        }
        return ajaxResult;
    }

    @Override
    @Transactional
    public AjaxResult updateOrdermessageAfterStatus(ArtOrderAfter artOrderAfter,ArtMessage artMessage) {
        AjaxResult ajaxResult = AjaxResult.success();
        /**
         * 实现思路？
         * 1. 校验参数
         * 2. 查询出订单来
         * 3.判断这个售后订单是什么类型然后进行对应的操作
         * */
        //查询出订单

        checkUpdateAfterStatusParams( artOrderAfter);
        String platAfterNo = artOrderAfter.getPlatAfterNo();
        ArtOrderAfter AfterOrder = artOrderAfterMapper.getAfterOrderByAfterOrderNo(platAfterNo);
        AfterOrder.setCompensationAmount(artOrderAfter.getCompensationAmount());
        if(AfterOrder == null){
            throw new RuntimeException("售后订单状态完结或不存在");
        }
        String platOrderNo = AfterOrder.getPlatOrderNo();
        ArtOrder artOrder = artOrderService.getOrderByOrderNo(platOrderNo);
        Long status = artOrderAfter.getStatus();
        if(2 == status.longValue()){//售后中
            ajaxResult =  updateAfterStatusToUnderway(AfterOrder,artOrder);
        }else if(3 == status.longValue()){//已完成  todo !!!
            ajaxResult = updatemessageAfterStatusToFinish(AfterOrder, artOrder,artMessage);
        }else if(4 == status.longValue()){  //已关闭
            ajaxResult = updateAfterStatusToClose(AfterOrder,artOrder);//暂时用不上
        }else if(5 == status.longValue()){//审核驳回
            ajaxResult = updateAfterStatusToReject(AfterOrder,artOrder);
        }else if(6 == status.longValue()){//已取消
            ajaxResult = updateAfterStatusToCancel(AfterOrder,artOrder);//暂时用不上，小程序用户用的，但可能用不上
        }
        return ajaxResult;
    }

    @Override
    public List<ArtOrderAfter> selectArtOrderAfterListByAfterType(ArtOrderAfter artOrderAfter) {
        return artOrderAfterMapper.selectArtOrderAfterListByAfterType(artOrderAfter);
    }
    //将售后订单设置为售后中
    public AjaxResult updatemessageAfterStatusToUnderway(ArtOrderAfter artOrderAfter,ArtOrder artOrder,ArtMessage artMessage){

        ArtOrderAfter update = new ArtOrderAfter();
        update.setId(artOrderAfter.getId());
        update.setStatus(IArtAfterLogService.ORDER_STATUS_IN_PROGRESS);
        update.setOpinion(artOrderAfter.getOpinion());//可能是空的
        artOrderAfterMapper.updateArtOrderAfter(update);
//        完成售后订单,创建消息
        artMessageMapper.completeAfterOrder(artMessage);
        artAfterLogService.createAfterLog(artOrderAfter.getPlatAfterNo(),
                IArtAfterLogService.OPERATE_RECEIVE,
                artOrderAfter.getUserId(),
                IArtAfterLogService.SYSTEM_USER_TYPE_SYS,
                IArtAfterLogService.ORDER_STATUS_IN_PROGRESS);
        return AjaxResult.success();
    }
    //将售后订单设置为售后中
    public AjaxResult updateAfterStatusToUnderway(ArtOrderAfter artOrderAfter,ArtOrder artOrder){

        ArtOrderAfter update = new ArtOrderAfter();
        update.setId(artOrderAfter.getId());
        update.setStatus(IArtAfterLogService.ORDER_STATUS_IN_PROGRESS);
        update.setOpinion(artOrderAfter.getOpinion());//可能是空的
        artOrderAfterMapper.updateArtOrderAfter(update);

        artAfterLogService.createAfterLog(artOrderAfter.getPlatAfterNo(),
                IArtAfterLogService.OPERATE_RECEIVE,
                artOrderAfter.getUserId(),
                IArtAfterLogService.SYSTEM_USER_TYPE_SYS,
                IArtAfterLogService.ORDER_STATUS_IN_PROGRESS);
        return AjaxResult.success();
    }
    //将售后订单设置为售后完成,赔偿
    public AjaxResult updatemessageAfterStatusToFinish(ArtOrderAfter artOrderAfter,ArtOrder artOrder,ArtMessage artMessage){
        String compensationAmount = artOrderAfter.getCompensationAmount(); //todo
        if(StringUtil.isEmpty(compensationAmount)){
            compensationAmount = "0";
        }
        artOrderAfter.setCompensationAmount(compensationAmount);

     /*   BigDecimal cBigD = new BigDecimal(compensationAmount);//补偿金额 平台录入的
        //实现思路
        BigDecimal orderAmount = new BigDecimal(0);//退款金额*/
        //1.加一个  解冻金额字段 、 用户补偿金额 、退款金额
        //2.先查询当前订单剩余的冻结金额还有多少
        //3.冻结金额 - 赔偿金额 = 解冻金额
        //4.赔偿是扣款动作 ，解冻是解冻动作

        // 1 orderAmount
        // 2 0

        IAfterRefund afterRefund  = null;
        //todo 售后完成后 处理订单逻辑
//        Long afterType = artOrderAfter.getAfterType();
//
//        if(afterType == 1 || afterType == 2||afterType == 3){
//            checkLogisticsParams(artOrderAfter);
//        }else if(afterType == 4) {
//            //这里什么都不做
//        }else{
//            throw new RuntimeException("售后类型错误");
//        }
//        if(artOrder.getRentalDays() != null && "1".equals(artOrder.getOrderType())) {
//            afterRefund = this.LeaseAfterRefund;
//        }else {
//            //购买
//            afterRefund = this.BuyAfterRefund;
//        }
//        AjaxResult update = afterRefund.afterRefund(artOrderAfter, artOrder);
//        修改售后状态为完成
        artMessage.setTitle(artOrder.getArtName());
        artMessage.setSender((long) 0 );
        artMessage.setReceiver(artOrderAfter.getUserId());
        artMessage.setStatus("0");
        artMessage.setSendTime(new Date());
        artMessage.setType("0");
        artMessage.setReceiver(artOrderAfter.getUserId());
        artOrderAfterMapper.completeOrderAfter(artOrderAfter.getPlatAfterNo());
        artMessage.setOrderNo(artOrderAfter.getPlatAfterNo());
        artMessageMapper.completeAfterOrder(artMessage);
        artAfterLogService.createAfterLog(artOrderAfter.getPlatAfterNo(),
                IArtAfterLogService.OPERATE_FINISH,
                artOrderAfter.getUserId(),
                IArtAfterLogService.SYSTEM_USER_TYPE_SYS,
                IArtAfterLogService.ORDER_STATUS_FINISH);
        return AjaxResult.success();
    }
    //将售后订单设置为售后完成
    public AjaxResult updateAfterStatusToFinish(ArtOrderAfter artOrderAfter,ArtOrder artOrder){
        String compensationAmount = artOrderAfter.getCompensationAmount(); //todo
        if(StringUtil.isEmpty(compensationAmount)){
            compensationAmount = "0";
        }
        artOrderAfter.setCompensationAmount(compensationAmount);

     /*   BigDecimal cBigD = new BigDecimal(compensationAmount);//补偿金额 平台录入的
        //实现思路
        BigDecimal orderAmount = new BigDecimal(0);//退款金额*/
        //1.加一个  解冻金额字段 、 用户补偿金额 、退款金额
        //2.先查询当前订单剩余的冻结金额还有多少
        //3.冻结金额 - 赔偿金额 = 解冻金额
        //4.赔偿是扣款动作 ，解冻是解冻动作

        // 1 orderAmount
        // 2 0

        IAfterRefund afterRefund  = null;
        //todo 售后完成后 处理订单逻辑
        Long afterType = artOrderAfter.getAfterType();

        if(afterType == 1 || afterType == 2||afterType == 3){
            checkLogisticsParams(artOrderAfter);
        }else if(afterType == 4) {
            //这里什么都不做
        }else{
         throw new RuntimeException("售后类型错误");
        }
        if(artOrder.getRentalDays() != null && "1".equals(artOrder.getOrderType())) {
            afterRefund = this.LeaseAfterRefund;
        }else {
            //购买
            afterRefund = this.BuyAfterRefund;
        }
        AjaxResult update = afterRefund.afterRefund(artOrderAfter, artOrder);

        artAfterLogService.createAfterLog(artOrderAfter.getPlatAfterNo(),
                IArtAfterLogService.OPERATE_FINISH,
                artOrderAfter.getUserId(),
                IArtAfterLogService.SYSTEM_USER_TYPE_SYS,
                IArtAfterLogService.ORDER_STATUS_FINISH);
        return AjaxResult.success();
    }
    public void checkLogisticsParams(ArtOrderAfter artOrderAfter){
        String nu = artOrderAfter.getNu();
        String com = artOrderAfter.getCom();
        String logisticsUrl = artOrderAfter.getLogisticsUrl();
        if(StringUtil.isEmpty(nu)){
            throw new RuntimeException("客户未填写运单号");
        }

        if(StringUtil.isEmpty(com)){
            throw new RuntimeException("客户未选择快递公司");
        }
        if(StringUtil.isEmpty(logisticsUrl)){
            throw new RuntimeException("客户未上传运单图片");
        }
    }
    //将售后订单设置为审核驳回
    public AjaxResult updateAfterStatusToReject(ArtOrderAfter artOrderAfter,ArtOrder artOrder){
        ArtOrderAfter update = new ArtOrderAfter();
        update.setId(artOrderAfter.getId());
        update.setStatus(IArtAfterLogService.ORDER_STATUS_REJECT);
        update.setOpinion(artOrderAfter.getOpinion());
        artOrderAfterMapper.updateArtOrderAfter(update);
        ArtOrder updateOrder = new ArtOrder();
        updateOrder.setOrderNo(artOrder.getOrderNo());
        updateOrder.setAfterStatus(2l);
        artOrderService.updateByOrderNo(updateOrder);
        artAfterLogService.createAfterLog(artOrderAfter.getPlatAfterNo(),
                IArtAfterLogService.OPERATE_REJECT,
                artOrderAfter.getUserId(),
                IArtAfterLogService.SYSTEM_USER_TYPE_SYS,
                IArtAfterLogService.ORDER_STATUS_REJECT);
        return AjaxResult.success();
    }
    //将售后订单设置为取消售后
    public AjaxResult updateAfterStatusToCancel(ArtOrderAfter artOrderAfter,ArtOrder artOrder){
        ArtOrderAfter update = new ArtOrderAfter();
        update.setId(artOrderAfter.getId());
        update.setStatus(IArtAfterLogService.ORDER_STATUS_CANCEL);

        artOrderAfterMapper.updateArtOrderAfter(update);
        ArtOrder updateOrder = new ArtOrder();
        updateOrder.setOrderNo(artOrder.getOrderNo());
        updateOrder.setAfterStatus(0l);
        artOrderService.updateByOrderNo(updateOrder);
        artAfterLogService.createAfterLog(artOrderAfter.getPlatAfterNo(),
                IArtAfterLogService.OPERATE_CANCEL,
                artOrderAfter.getUserId(),
                IArtAfterLogService.SYSTEM_USER_TYPE_APP,
                IArtAfterLogService.ORDER_STATUS_CANCEL);
        return AjaxResult.success();
    }
    //将售后订单设置为已关闭
    public AjaxResult updateAfterStatusToClose(ArtOrderAfter artOrderAfter,ArtOrder artOrder){
        ArtOrderAfter update = new ArtOrderAfter();
        update.setId(artOrderAfter.getId());
        update.setStatus(IArtAfterLogService.ORDER_STATUS_CLOSE);

        artOrderAfterMapper.updateArtOrderAfter(update);

        artAfterLogService.createAfterLog(artOrderAfter.getPlatAfterNo(),
                IArtAfterLogService.OPERATE_CLOSE,
                artOrderAfter.getUserId(),
                IArtAfterLogService.SYSTEM_USER_TYPE_SYS,
                IArtAfterLogService.ORDER_STATUS_CLOSE);
        return AjaxResult.success();
    }

    public void checkUpdateAfterStatusParams(ArtOrderAfter artOrderAfter){
        String platAfterNo = artOrderAfter.getPlatAfterNo();
        Long status = artOrderAfter.getStatus();
        artOrderAfter.getOpinion();
        if(StringUtil.isEmpty(platAfterNo)){
            throw new RuntimeException("请填写售后单号");
        }
        if(null == status){
            throw new RuntimeException("请选择审核状态");
        }

        if(5 == status.longValue() && StringUtil.isEmpty(artOrderAfter.getOpinion())){
            throw new RuntimeException("请填写审核意见");
        }
    }
    @Override
    @Transactional
    public void updateOrderAfterLogisticsInfo(ArtOrderAfter artOrderAfter) {
       //校验参数
        checkUpdateOrderParams(artOrderAfter);

        //增加售后操作记录
        ArtOrderAfter sel = artOrderAfterMapper.getAfterOrderByAfterOrderNo(artOrderAfter.getPlatAfterNo());
        if(sel == null){
            throw new RuntimeException("售后订单不存在");
        }

        ArtServiceCharge artServiceCharge = artServiceChargeMapper.selectByOrderNo(artOrderAfter.getPlatOrderNo());
        if(artServiceCharge != null && "0".equals(artServiceCharge.getStatus())){
            artOrderService.serviceChargeUtil(artServiceCharge);
        }

        //更新售后订单信息
        artOrderAfterMapper.updateOrderAfterLogisticsInfo(artOrderAfter);
        artAfterLogService.createAfterLog(artOrderAfter.getPlatAfterNo(),
                IArtAfterLogService.OPERATE_SEND_OUT_GOODS,
                artOrderAfter.getUserId(),
                IArtAfterLogService.SYSTEM_USER_TYPE_APP,
                sel.getStatus());
    }
    private void checkUpdateOrderParams(ArtOrderAfter artOrderAfter){
        String platAfterNo = artOrderAfter.getPlatAfterNo();
        String logisticsUrl = artOrderAfter.getLogisticsUrl();
        String nu = artOrderAfter.getNu();
        String com = artOrderAfter.getCom();
        Long userId = artOrderAfter.getUserId();
        if(StringUtil.isEmpty(platAfterNo)){
            throw new RuntimeException("请填写售后单号");
        }
        if(StringUtil.isEmpty(logisticsUrl)){
            throw new RuntimeException("请填写物流单图片");
        }
        if(StringUtil.isEmpty(nu)){
            throw new RuntimeException("请填写物流单号");
        }
        if(StringUtil.isEmpty(com)){
            throw new RuntimeException("请填写物流公司");
        }
        if(null == userId){
            throw new RuntimeException("未找到用户");
        }
    }
    @Override
    @Transactional
    public void createOrderAfter(ArtOrderAfter artOrderAfter) {
        String platOrderNo = artOrderAfter.getPlatOrderNo();//用户下单的订单号
        Long userId = artOrderAfter.getUserId();
        String explain = artOrderAfter.getExplain();
        if(StringUtil.isEmpty(explain)){
            throw new RuntimeException("请填写售后原因");
        }
        //查出订单 //根据用户id 和 订单号查
        ArtOrder artOrder =   artOrderService.getOrderByOrderNo(platOrderNo);
        if( artOrder == null){ //判断订单是否存在
            throw new RuntimeException("订单不存在");
        }
        Long takStatus = artOrder.getTakStatus();
        if(1l == takStatus.longValue()){
            throw new RuntimeException("订单已开票，不能申请售后");
        }
        Long orderUserId = artOrder.getUserId();
        if(userId.longValue()!= orderUserId.longValue()){
            throw new RuntimeException("订单不属于当前用户");
        }
        ArtOrderAfter sel = artOrderAfterMapper.getAfterOrderByOrderNo(platOrderNo);
        if(null!= sel){ //判断订单是否已经售后
            throw new RuntimeException("订单已经售后");
        }
        //是否允许售后
        checkAllowAfter(artOrder,artOrderAfter);

        String platAfterNo = MyIncrementGenerator.uuid(21);
        //新增售后记录
        ArtOrderAfter insert = new ArtOrderAfter();
        insert.setPlatOrderNo(platOrderNo);//商品订单号
        insert.setOrderGoodsId(artOrder.getArtRentalId());//订单商品的id
        insert.setPlatAfterNo(platAfterNo);//售后订单编号
        insert.setUserId(userId);//用户id
        insert.setAfterType(artOrderAfter.getAfterType());
        insert.setAfterNum(artOrder.getGoodsNum());
        insert.setExplain(explain);

        // insert.setRefundMoney();//退款金额  -- 这里不设置退款金额，在审核通过后计算 退款金额
        if(artOrderAfter.getAfterType() == 2l){
            // 如果是归还的操作，直接将订单状态改为售后中，不需要审核
            insert.setStatus(2l);

            // 已过7天无理由但未满1个月退还，租金还未扣除的情况下，需缴纳服务费（一个月租金）
            // 把订单号放到扣款记录表中，扣除服务费
            // 签收日大于7天，并且没有订单金额order_amount=null的情况下，需要扣除服务费
            // 获取当前日期
            Date currentDate = new Date();
            // 创建Calendar对象，用于操作日期
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(artOrder.getSignDate());

            // 将signDate加上7天
            calendar.add(Calendar.DATE, 7);
            Date signDatePlus7Days = calendar.getTime();
            if(currentDate.after(signDatePlus7Days) && artOrder.getOrderAmount() == null){
                ArtServiceCharge serviceCharge = new ArtServiceCharge();
                serviceCharge.setOrderNo(platOrderNo);
                serviceCharge.setStatus("0");
                serviceCharge.setCreateTime(new Date());
                artServiceChargeMapper.insert(serviceCharge);
            }
        }else{
            insert.setStatus(IArtAfterLogService.ORDER_STATUS_WAIT_CHECK);
        }
        artOrder.setAfterStatus(1l);// 售后状态 1= 售后

        int i = artOrderService.updateByOrderNo(artOrder);

        artOrderAfterMapper.insertArtOrderAfter(insert);
        //增加售后操作记录
        artAfterLogService.createAfterLog(platAfterNo,
                IArtAfterLogService.OPERATE_CREATE,
                userId,
                IArtAfterLogService.SYSTEM_USER_TYPE_APP,
                IArtAfterLogService.ORDER_STATUS_WAIT_CHECK);

    }
    private void checkAllowAfter(ArtOrder artOrder,ArtOrderAfter artOrderAfter){
        Long afterType = artOrderAfter.getAfterType();
        if(null == afterType){
            throw new RuntimeException ("请选择售后类型");
        }
        // 1=退货退款，2=归还，3=提前归还 4 =仅退款
        if(1 == afterType.longValue()){
            Date deliveryDate = artOrder.getDeliveryDate();//发货日期
            Date signDate = artOrder.getSignDate();//签收日期
            //当前时间
            Date now = new Date();
            if(null == deliveryDate ){
                throw new RuntimeException("订单未发货，不能申请退货退款");
            }
            //判断当前时间是否在签收日期的7天以内
            // 假设签收日期为 '2023-10-01'
            // 判断当前时间是否在签收日期7天以内
            if(null != signDate ){
                if (!isWithinSevenDays(signDate, now)) {
                    throw new RuntimeException("订单超过售后时间，不能申请退货退款");
                }
            }
        }else if(2 == afterType.longValue()){
            Date signDate = artOrder.getSignDate();//签收日期
            Date now = new Date();
            Date rentalEndDate = artOrder.getRentalEndDate();//租赁到期时间
            //将当前时间和租赁到期时间格式化为 日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            //Date rentalEndDate 转换为 yyyy-MM-dd 格式的字符串
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            LocalDate rentalEndDateL = LocalDate.parse(sdf.format(rentalEndDate));
            LocalDate nowL = LocalDate.parse(sdf.format(now));
            if(null == rentalEndDate){
                throw new RuntimeException("订单未租赁，不能申请归还");
            }
            //判断当前时间是否未超过，如果没有租赁到期时间，则不允许申请归还
//            if(nowL.isBefore(rentalEndDateL)){
//                 throw new RuntimeException("未到租赁结束日期，不能申请归还");
//            }

            //判断当前时间是否在签收日期的7天以内
           /* if(null != signDate ){
                if (!isWithinSevenDays(signDate, now)) {
                    throw new RuntimeException("订单超过售后时间，不能申请归还");
                }
            }*/
        }else if(3 == afterType.longValue()){
            if(artOrder.getParentOrderNo() == null) {
                Date signDate = artOrder.getSignDate();//签收日期
                Date now = new Date();
                if (null == signDate) {
                    throw new RuntimeException("订单未签收，不能申请归还");
                }
                // 判断当前日期是否超过签收日期7天
                if (!isMoreThanSevenDays(signDate, now)) {
                    throw new RuntimeException("订单超过售后时间，不能申请退货退款");
                }
            }
        }else if(4 == afterType.longValue()){
            Date deliveryDate = artOrder.getDeliveryDate();
            if(null!= deliveryDate){
                throw new RuntimeException("订单已发货，不能申请仅退款");
            }
        }else {
            throw new RuntimeException("售后类型错误");
        }
    }

    private static boolean isMoreThanSevenDays(Date signDate, Date now) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(signDate);
        calendar.add(Calendar.DAY_OF_YEAR, 7);
        Date sevenDaysLater = calendar.getTime();

        return now.after(sevenDaysLater);
    }
    private static boolean isWithinSevenDays(Date signDate, Date now) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(signDate);
        calendar.add(Calendar.DAY_OF_YEAR, 7);
        Date sevenDaysLater = calendar.getTime();

        return now.after(signDate) && now.before(sevenDaysLater);
    }
    @Override
    public ArtOrderAfter getOrderAfterInfo(String orderNo) {
        return artOrderAfterMapper.getLatestAfterOrderByOrderNo(orderNo);
    }

    /**
     * 查询售后订单
     *
     * @param id 售后订单主键
     * @return 售后订单
     */
    @Override
    public ArtOrderAfter selectArtOrderAfterById(Long id)
    {
        return artOrderAfterMapper.selectArtOrderAfterById(id);
    }

    /**
     * 查询售后订单列表
     *
     * @param artOrderAfter 售后订单
     * @return 售后订单
     */
    @Override
    public List<ArtOrderAfter> selectArtOrderAfterList(ArtOrderAfter artOrderAfter)
    {
        return artOrderAfterMapper.selectArtOrderAfterList(artOrderAfter);
    }

    /**
     * 新增售后订单
     *
     * @param artOrderAfter 售后订单
     * @return 结果
     */
    @Override
    public int insertArtOrderAfter(ArtOrderAfter artOrderAfter)
    {
        return artOrderAfterMapper.insertArtOrderAfter(artOrderAfter);
    }

    /**
     * 修改售后订单
     *
     * @param artOrderAfter 售后订单
     * @return 结果
     */
    @Override
    public int updateArtOrderAfter(ArtOrderAfter artOrderAfter)
    {
        return artOrderAfterMapper.updateArtOrderAfter(artOrderAfter);
    }

    /**
     * 批量删除售后订单
     *
     * @param ids 需要删除的售后订单主键
     * @return 结果
     */
    @Override
    public int deleteArtOrderAfterByIds(Long[] ids)
    {
        return artOrderAfterMapper.deleteArtOrderAfterByIds(ids);
    }

    /**
     * 删除售后订单信息
     *
     * @param id 售后订单主键
     * @return 结果
     */
    @Override
    public int deleteArtOrderAfterById(Long id)
    {
        return artOrderAfterMapper.deleteArtOrderAfterById(id);
    }
}
